package com.tian.photopicker.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import com.tian.photopicker.R;
import com.tian.photopicker.bean.Photo;
import com.tian.photopicker.data.MediaStoreHelper;
import com.tian.photopicker.util.AndroidLifecycleUtils;
import com.tian.photopicker.util.Selectable;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片选择适配器
 * @author tian
 */

public class PickerGridAdapter extends RecyclerView.Adapter<PickerGridAdapter.PickerHolder>
                implements Selectable {
    private boolean showCamera = true;
    private RequestManager glide;
    private List<Photo> mData;
    private Context context;
    private int imageSize;
    public int currentDirectoryIndex = 0;
    public final static int ITEM_TYPE_CAMERA = 100;
    public final static int ITEM_TYPE_PHOTO  = 101;
    private View.OnClickListener onCameraClickListener = null;
    private OnItemCheckListener onItemCheckListener    = null;
    private OnPhotoClickListener onPhotoClickListener  = null;
    private List<String> selectPhotos;
    public PickerGridAdapter(Context context, RequestManager requestManager, List<Photo> dataList) {
        this.context = context;
        this.mData = dataList;
        this.glide = requestManager;
        selectPhotos = new ArrayList<>();
        setColumnNumber(context,3);
    }

    public void setOnCameraClickListener(View.OnClickListener onCameraClickListener) {
        this.onCameraClickListener = onCameraClickListener;
    }

    public void setOnItemCheckListener(OnItemCheckListener onItemCheckListener) {
        this.onItemCheckListener = onItemCheckListener;
    }

    public void setOnPhotoClickListener(OnPhotoClickListener onPhotoClickListener) {
        this.onPhotoClickListener = onPhotoClickListener;
    }

    /**
     * 设置图片宽高
     * @param context
     * @param i
     */
    private void setColumnNumber(Context context, int i) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
        int widthPixels = metrics.widthPixels;
        imageSize = widthPixels / i;
    }

    @Override
    public PickerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = View.inflate(context,R.layout.item_picker_layout,null);
        PickerHolder holder = new PickerHolder(itemView);
        if (viewType == ITEM_TYPE_CAMERA) {
            holder.vSelected.setVisibility(View.GONE);
            holder.ivPhoto.setScaleType(ImageView.ScaleType.CENTER);
            holder.ivPhoto.setOnClickListener(new View.OnClickListener() {
                @Override public void onClick(View view) {
                    if (onCameraClickListener != null) {
                        onCameraClickListener.onClick(view);
                    }
                }
            });
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(final PickerHolder holder, final int position) {
        if (getItemViewType(position) == ITEM_TYPE_PHOTO) {
            final Photo photo;
            if (showCamera()) {
                photo = mData.get(position - 1);
            } else {
                photo = mData.get(position);
            }
            boolean canLoadImage = AndroidLifecycleUtils.canLoadImage(holder.ivPhoto.getContext());

            if (canLoadImage) {
                final RequestOptions options = new RequestOptions();
                options.centerCrop()
                        .dontAnimate()
                        .override(imageSize, imageSize)
                        .placeholder(R.drawable.icon_place_holder)
                        .error(R.drawable.icon_place_holder);

                glide.setDefaultRequestOptions(options)
                        .load(new File(photo.getPath()))
                        .thumbnail(0.5f)
                        .into(holder.ivPhoto);
            }

            final boolean isChecked = isSelected(photo);

            holder.vSelected.setSelected(isChecked);
            //holder.ivPhoto.setSelected(isChecked);
            holder.ivPhoto.setOnClickListener(new View.OnClickListener() {
                @Override public void onClick(View view) {
               onPhotoClickListener.onClick(view,position,showCamera());
                }
            });
            holder.vSelected.setOnClickListener(new View.OnClickListener() {
                @Override public void onClick(View view) {
                    int pos = holder.getAdapterPosition();
                    boolean isEnable = true;
                    if (onItemCheckListener != null) {
                        isEnable = onItemCheckListener.onItemCheck(pos, photo,
                                getSelectedPhotos().size() + (isSelected(photo) ? -1: 1));
                    }
                    if (isEnable) {
                        toggleSelection(photo);
                        notifyItemChanged(pos);
                    }
                }
            });

        } else {
            holder.ivPhoto.setImageResource(R.drawable.camera);
        }
    }

    @Override
    public int getItemViewType(int position) {
        return (showCamera() && position == 0) ? ITEM_TYPE_CAMERA:ITEM_TYPE_PHOTO;
    }

    @Override
    public int getItemCount() {
        int photosCount = mData.size();
        if (showCamera()) {
            return photosCount + 1;
        }
        return photosCount;
    }

    @Override
    public boolean isSelected(Photo photo) {
        return getSelectedPhotos().contains(photo.getPath());
    }
    public boolean isSelectedPath (String photo) {
        return getSelectedPhotos().contains(photo);
    }
    @Override
    public void toggleSelection(Photo photo) {
        if (selectPhotos.contains(photo.getPath())) {
            selectPhotos.remove(photo.getPath());
        } else {
            selectPhotos.add(photo.getPath());
        }
    }

    @Override
    public void clearSelection() {
        selectPhotos.clear();
    }

    @Override
    public int getSelectedItemCount() {
        return selectPhotos.size();
    }

    public ArrayList<String> getSelectedPhotoPaths() {
        ArrayList<String> selectedPhotoPaths = new ArrayList<>(getSelectedItemCount());
        for (String photo : selectPhotos) {
            selectedPhotoPaths.add(photo);
        }
        return selectedPhotoPaths;
    }

    class PickerHolder extends RecyclerView.ViewHolder {
        private ImageView ivPhoto;
        private ImageView vSelected;
        public PickerHolder(View itemView) {
            super(itemView);
            ivPhoto   = (ImageView) itemView.findViewById(R.id.iv_photo);
            vSelected = (ImageView) itemView.findViewById(R.id.v_selected);
        }
    }
    public void setShowCamera(boolean showCamera) {
        this.showCamera = showCamera;
    }

    @Override
    public void onViewRecycled(PickerHolder holder) {
        glide.clear(holder.ivPhoto);
        super.onViewRecycled(holder);
    }
    public boolean showCamera() {
        return (showCamera && currentDirectoryIndex == MediaStoreHelper.INDEX_ALL_PHOTOS);
    }

    public interface OnItemCheckListener {
        /***
         *
         * @param position 所选图片的位置
         * @param path     所选的图片
         * @param selectedItemCount  已选数量
         * @return enable check
         */
        boolean onItemCheck(int position, Photo path, int selectedItemCount);

    }
    public interface OnPhotoClickListener {

        void onClick(View v, int position, boolean showCamera);
    }
    public List<String> getSelectedPhotos() {
        return selectPhotos;
    }

    /**
     * 用户判断是不是所有 显不显示照相机
     * @param currentDirectoryIndex
     */
    public void setCurrentDirectoryIndex(int currentDirectoryIndex) {
        this.currentDirectoryIndex = currentDirectoryIndex;
    }
    public void setNewData (List<Photo> data) {
        this.mData = data;
        notifyDataSetChanged();
    }
    public List<String> getCurrentPhotoPaths() {
        List<String> currentPhotoPaths = new ArrayList<>(mData.size());
        for (Photo photo : mData) {
            currentPhotoPaths.add(photo.getPath());
        }
        return currentPhotoPaths;
    }

}
